package com.the_last.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.the_last.mapper.ProductCategoryMapper;
import com.the_last.pojo.po.ProductCategory;
import com.the_last.service.ProductCategoryService;
import com.the_last.utils.RedisUtil;
import com.the_last.utils.Result;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @description 针对表【product_category】的数据库操作Service实现
 */
@Service
@Slf4j
public class ProductCategoryServiceImpl extends ServiceImpl<ProductCategoryMapper, ProductCategory>
        implements ProductCategoryService {
    
    @Resource
    private RedisUtil redisUtil;
    
    @Resource
    private RedissonClient redissonClient;
    
    /**
     * 清除商品类别缓存
     */
    private void clearCategoryCache() {
        redisUtil.delete("product:category:all");
    }
    
    @Override
    public Result<List<ProductCategory>> getAllCategories() {
        // 缓存key
        String cacheKey = "product:category:all";
        
        // 尝试从缓存获取
        List<ProductCategory> cached = redisUtil.getList(cacheKey, ProductCategory.class);
        if (!CollectionUtils.isEmpty(cached)) {
            return Result.success(cached);
        }
        
        // 获取分布式锁
        String lockKey = "lock:product:category:all";
        RLock lock = redissonClient.getLock(lockKey);
        
        try {
            lock.lock();
            
            // 双重检查
            cached = redisUtil.getList(cacheKey, ProductCategory.class);
            if (!CollectionUtils.isEmpty(cached)) {
                return Result.success(cached);
            }
            
            // 从数据库查询
            List<ProductCategory> list = this.lambdaQuery()
                    .eq(ProductCategory::getDeleted, 0)  // 只查询未删除的
                    .orderByAsc(ProductCategory::getId)
                    .list();
            
            // 存入缓存
            if (!CollectionUtils.isEmpty(list)) {
                redisUtil.setList(cacheKey, list);
            }
            
            return Result.success(list);
        } finally {
            lock.unlock();
        }
    }
    
    /**
     * 更新商品类别
     */
    public Result<String> updateCategory(ProductCategory category) {
        if (category == null || category.getId() == null) {
            return Result.fail("商品类别信息不能为空");
        }
        
        try {
            // 获取原有数据
            ProductCategory existingCategory = getById(category.getId());
            if (existingCategory == null) {
                return Result.fail("商品类别不存在");
            }
            
            // 检查名称是否发生变化
            boolean nameChanged = !existingCategory.getName().equals(category.getName());
            
            // 更新到数据库
            boolean success = updateById(category);
            if (success) {
                // 只有当名称发生变化时才清除缓存
                if (nameChanged) {
                    clearCategoryCache();
                }
                return Result.success("商品类别更新成功");
            } else {
                return Result.fail("商品类别更新失败");
            }
        } catch (Exception e) {
            log.error("更新商品类别失败", e);
            return Result.fail("更新商品类别失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除商品类别
     */
    public Result<Void> deleteCategory(Integer id) {
        if (id == null) {
            return Result.fail("商品类别ID不能为空");
        }
        
        try {
            boolean success = removeById(id);
            if (success) {
                clearCategoryCache();
                return Result.success();
            } else {
                return Result.fail("删除商品类别失败");
            }
        } catch (Exception e) {
            log.error("删除商品类别失败", e);
            return Result.fail("删除商品类别失败：" + e.getMessage());
        }
    }
}